package com.fengyunhe.manager.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * 功能：国际化资源JS
 * 作者： yangyan
 * 时间： 2014/11/23 .
 */
@Controller
@RequestMapping
public class LocaleController extends AdminBaseController {


    @Resource
    MessageSource messageSource;
    ResourceBundle message = ResourceBundle.getBundle("message");

    ObjectMapper m = new ObjectMapper();

    /**
     * 输出国际化的JS全局变量
     *
     * @param request
     * @param response
     * @throws com.fasterxml.jackson.core.JsonProcessingException
     */
    @RequestMapping("i18n")
    @ResponseBody
    public void js(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
        HttpSession session =  request.getSession();
        Locale locale = RequestContextUtils.getLocale(request);
        Set<String> strings = message.keySet();
        Map<String, String> messages = new HashMap<String, String>();

        for (String string : strings) {
            messages.put(string, messageSource.getMessage(string, null, locale));
        }
        response.setContentType("application/javascript;charset=utf-8");

        String json = m.writeValueAsString(messages);
        try {
            response.getWriter().println("I18N=" + json);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改语言
     */
    @RequestMapping("locale")
    @ResponseBody
    public void changeLocale() {
    }
}
